package cn.jiyun.user.service.impl;

import cn.jiyun.user.common.R;
import cn.jiyun.user.dao.UserDao;
import cn.jiyun.user.pojo.User;
import cn.jiyun.user.pojo.dto.UserDto;
import cn.jiyun.user.service.UserService;
import cn.jiyun.user.utils.AppJwtUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public R login(UserDto userDto) {
        String prefix = "login_user_";
        User user=null;
        if(StringUtils.isEmpty(userDto.getUserName())||StringUtils.isEmpty(userDto.getPassword()+"")){
            return R.error("用户名或密码不能为空");
        }
        //存在id
        if(userDto.getId()!=null){
            //查询redis
            Boolean hashKey = redisTemplate.hasKey(prefix + userDto.getId());
            if(hashKey){
                String userJson = redisTemplate.opsForValue().get(prefix + userDto.getId());
                user= JSON.parseObject(userJson,User.class);
            }
        }else {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name",userDto.getUserName()).eq("password", userDto.getPassword());
            user = userDao.selectOne(queryWrapper);
            if(Optional.ofNullable(user).isPresent()){
                //将用户信息存到redis中
                //login_user_
                redisTemplate.opsForValue().set(prefix+user.getId(),JSON.toJSONString(user));
            }else {
                return R.error("用户名或密码错误");
            }
        }
        String token = AppJwtUtil.getToken(user.getId());
        HashMap<String, String> map = new HashMap<>();
        map.put("user",JSON.toJSONString(user));
        map.put("token",token);
        return R.success(map);
    }
}
